<template>
    <div class="dining-feedback-admin">
        <el-card v-loading="loading">
            <template #header>
                <div class="card-header">
                    <span>需求反馈管理</span>
                </div>
            </template>
            
            <!-- 需求反馈列表 -->
            <el-tabs v-model="activeTab">
                <el-tab-pane label="未处理" name="unhandled">
                    <el-empty v-if="unhandledList.length === 0" description="暂无未处理的反馈" />
                    <el-timeline v-else>
                        <el-timeline-item
                            v-for="feedback in unhandledList"
                            :key="feedback.id"
                            type="warning"
                            :timestamp="formatTime(feedback.createTime)"
                        >
                            <el-card class="feedback-item">
                                <h4>用户：{{ feedback.userName }}</h4>
                                <h4>需求内容：</h4>
                                <p>{{ feedback.content }}</p>
                                <el-input
                                    type="textarea"
                                    v-model="feedback.replyContent"
                                    :rows="3"
                                    placeholder="请输入回复内容"
                                />
                                <div class="button-group">
                                    <el-button type="primary" @click="handleReply(feedback)">回复</el-button>
                                </div>
                            </el-card>
                        </el-timeline-item>
                    </el-timeline>
                </el-tab-pane>
                
                <el-tab-pane label="已处理" name="handled">
                    <el-empty v-if="handledList.length === 0" description="暂无已处理的反馈" />
                    <el-timeline v-else>
                        <el-timeline-item
                            v-for="feedback in handledList"
                            :key="feedback.id"
                            type="success"
                            :timestamp="formatTime(feedback.createTime)"
                        >
                            <el-card class="feedback-item">
                                <h4>用户：{{ feedback.userName }}</h4>
                                <h4>需求内容：</h4>
                                <p>{{ feedback.content }}</p>
                                <h4>回复内容：</h4>
                                <p>{{ feedback.reply }}</p>
                                <p class="reply-time">回复时间：{{ formatTime(feedback.replyTime) }}</p>
                            </el-card>
                        </el-timeline-item>
                    </el-timeline>
                </el-tab-pane>
            </el-tabs>
        </el-card>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from '../../../utils/axios'

const loading = ref(false)
const activeTab = ref('unhandled')
const unhandledList = ref([])
const handledList = ref([])

// 获取需求反馈列表
const loadFeedbacks = async () => {
    try {
        loading.value = true;
        console.log('开始加载反馈列表...')
        
        // 获取已处理的反馈
        const handledResponse = await axios.get('/dining/feedback/handled')
        console.log('已处理反馈原始响应:', handledResponse)
        console.log('已处理反馈数据结构:', {
            code: handledResponse.data.code,
            message: handledResponse.data.message,
            result: handledResponse.data.result
        })
        
        if (handledResponse.data.code === 200) {
            // 确保result是数组
            const handledData = Array.isArray(handledResponse.data.result.records) ? handledResponse.data.result.records : [];
            console.log('已处理数据详情:', handledResponse)
            
            // 检查数据结构
            if (handledData.length > 0) {
                console.log('第一条已处理数据示例:', {
                    原始数据: handledData[0],
                    id: handledData[0].id,
                    userId: handledData[0].userId,
                    content: handledData[0].content,
                    reply: handledData[0].reply,
                    user: handledData[0].user,
                    createTime: handledData[0].createTime
                })
            }
            
            handledList.value = handledData.map(item => {
                const mappedItem = {
                    id: item.id,
                    userId: item.userId,
                    content: item.content || '',
                    createTime: item.createTime,
                    replyTime: item.replyTime,
                    userName: item.user?.name || `用户${item.userId}`,
                    reply: item.reply || '' // 直接使用reply字段
                };
                console.log(`处理反馈项 ${item.id} 的数据:`, mappedItem);
                return mappedItem;
            })
            // 按照创建时间降序排序，确保最新的在前面
            .sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
            
            console.log('最终处理后的已处理列表:', handledList.value)
        } else {
            console.warn('获取已处理反馈失败:', handledResponse.data)
            ElMessage.warning(handledResponse.data.message || '获取已处理反馈失败')
            handledList.value = []
        }

        // 获取未处理的反馈
        const unhandledResponse = await axios.get('/dining/feedback/unhandled')
        console.log('未处理反馈响应:', unhandledResponse)
        if (unhandledResponse.data.code === 200) {
            // 确保result是数组
            const unhandledData = Array.isArray(unhandledResponse.data.result) ? unhandledResponse.data.result : [];
            console.log('未处理数据:', unhandledData)
            unhandledList.value = unhandledData.map(item => ({
                id: item.id,
                userId: item.userId,
                content: item.content || '',
                createTime: item.createTime,
                replyContent: '',
                userName: item.user?.name || `用户${item.userId}`,
                reply: item.reply || ''
            }))
            // 按照创建时间降序排序，确保最新的在前面
            .sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
        } else {
            console.warn('获取未处理反馈失败:', unhandledResponse.data)
            ElMessage.warning(unhandledResponse.data.message || '获取未处理反馈失败')
            unhandledList.value = []
        }
    } catch (error) {
        console.error('加载反馈失败:', error);
        ElMessage.error('加载反馈失败: ' + (error.response?.data?.message || error.message));
        unhandledList.value = []
        handledList.value = []
    } finally {
        loading.value = false;
    }
}

// 回复需求
const handleReply = async (feedback) => {
    if (!feedback?.id) {
        console.error('反馈数据无效:', feedback)
        ElMessage.error('反馈数据无效')
        return
    }

    if (!feedback.replyContent) {
        ElMessage.warning('请输入回复内容')
        return
    }
    
    try {
        // 构建请求数据，直接提交为DiningFeedback对象格式
        const replyData = {
            id: feedback.id,
            reply: feedback.replyContent,
            status: 1
        };
        console.log('提交回复数据:', replyData)

        console.log('开始发送回复请求...');
        // 恢复使用原始接口
        const response = await axios.put('/dining/feedback/reply', replyData);
        
        console.log('回复响应详情:', {
            状态码: response.status,
            响应数据: response.data,
            请求数据: replyData
        })

        if (response.data.code === 200) {
            ElMessage.success('回复成功')
            console.log('准备重新加载数据...');
            
            // 强制切换到已处理列表以查看刚刚处理的反馈
            activeTab.value = 'handled';
            
            // 在DOM更新后再调用加载数据
            setTimeout(() => {
                loadFeedbacks().then(() => {
                    console.log('数据重新加载完成');
                    console.log('未处理列表数量:', unhandledList.value.length);
                    console.log('已处理列表数量:', handledList.value.length);
                }).catch(err => {
                    console.error('数据重新加载失败:', err);
                });
            }, 300); // 增加延迟时间
        } else {
            console.warn('回复失败:', response.data)
            ElMessage.error(response.data.message || '回复失败')
        }
    } catch (error) {
        console.error('回复失败:', error)
        console.error('错误详情:', {
            message: error.message,
            response: error.response?.data,
            status: error.response?.status,
            config: error.config,
            stack: error.stack
        })
        
        // 显示更详细的错误信息
        let errorMsg = '回复失败';
        if (error.response?.data?.message) {
            errorMsg += ': ' + error.response.data.message;
        } else if (error.message) {
            errorMsg += ': ' + error.message;
        }
        
        ElMessage.error(errorMsg);
    }
}

// 格式化时间
const formatTime = (time) => {
    if (!time) return '-'
    try {
        const date = new Date(time)
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    } catch (error) {
        console.error('时间格式化失败:', error)
        return time
    }
}

onMounted(() => {
    loadFeedbacks()
})
</script>

<style scoped>
.dining-feedback-admin {
    padding: 20px;
}

.card-header {
    font-weight: bold;
}

.feedback-item {
    margin-bottom: 10px;
}

.feedback-item h4 {
    margin: 10px 0;
    color: #666;
}

.feedback-item p {
    margin: 5px 0;
    line-height: 1.5;
    white-space: pre-wrap;
}

.button-group {
    margin-top: 10px;
    text-align: right;
}

.reply-time {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
}

.el-timeline {
    margin-top: 20px;
}

.el-input {
    margin: 10px 0;
}

.el-empty {
    padding: 20px 0;
}
</style> 